from datetime import datetime
from functools import wraps
from typing import Any, Callable, Dict, Optional
import logging

logger = logging.getLogger(__name__)

def validate_paper_fields(func: Callable) -> Callable:
    """改进的字段验证装饰器"""
    @wraps(func)
    def wrapper(self, paper: Dict[str, Any], *args, **kwargs):
        required = ['title', 'content', 'venue', 'year']
        
        # 检查content是否为空
        if not paper.get('content'):
            # 尝试从其他可能的字段获取内容
            for field in ['chunk_text', 'text', 'abstract']:
                if paper.get(field):
                    paper['content'] = paper[field]
                    break
        
        missing = [f for f in required if not paper.get(f)]
        if missing:
            logger.warning(f"论文缺失关键字段: {missing}")
            return None
            
        # 验证内容长度
        if len(str(paper['content']).strip()) < 100:  # 最小内容长度要求
            logger.warning("内容长度不足")
            return None
            
        return func(self, paper, *args, **kwargs)
    return wrapper

class YearValidator:
    """年份验证器"""
    
    def __init__(self, min_year: int = 1990):
        self.min_year = min_year
        self.max_year = datetime.now().year
        
    def validate(self, year: Any) -> Optional[int]:
        """验证并规范化年份"""
        if year is None:
            return self.max_year
            
        try:
            if isinstance(year, str):
                year = int(''.join(filter(str.isdigit, year)))
            elif isinstance(year, (int, float)):
                year = int(year)
            else:
                return self.max_year

            return year if self.min_year <= year <= self.max_year else self.max_year
            
        except (ValueError, TypeError):
            return self.max_year
